<extend name="common/base" />
<taglib name="CMS\TagLib\Zui" />

<block name="body">
<div style="height: 5px;"></div>
<div class="col-sm-8">
    <div class="panel">
        <div class="panel-heading">分类树</div>
        <div class="panel-body">
	        <ul id="categories_index" class="ztree"
		        data-toggle="ztree"
		        data-options="{
		            editEnable: true,
		            showRenameBtn: false,
		            showRemoveBtn: false,
		            addHoverDom: 'edit',
		            removeHoverDom: 'edit',
		            beforeDrag: M_BeforeNodeDrag,
		            beforeDrop: M_BeforeNodeDrop,
		            onDrop: M_NodeDrop,
		            onRemove: M_NodeRemove,
		            nodes:{$list|json_encode|str_replace='"',"'",###},
		            expandAll: true,
		            setting: {
		                key: {
		                    children: 'sub',
		                    name: 'catname',
		                },
		                data: {
		                    key: {
		                        children: 'sub',
		                        name: 'catname',
		                    },
		                    simpleData: {
		                        enable: true,
		                        idKey: 'catid',
		                        pIdKey: 'upid',
		                    },
		                },
		                callback: {
		                    onClick:ZtreeClick
		                }
		            }
		        }">
	        </ul>
	    </div>
	</div>
</div>
<div id="ztree-detail" class="col-sm-4">
    <div class="panel">
        <div class="panel-heading">分类信息</div>
        <div class="panel-body">
            <form action="{:url('update')}" data-toggle="validate" id="category_data">
                <div class="form-group">
                    <div class="input-group">
                        <zui:input type="text" name="catname" title="分类名称" required="true" /></div>
                </div>
                <div class="form-group">
                    <div class="input-group">
                        <zui:input type="text" name="upid" title="上级分类ID" readonly='true' /></div>
                </div>
                <div class="form-group">
                    <div class="input-group">
                        <zui:radio name="allowpublish" radios="yesorno" title="允许发布文章" /></div>
                </div>
                <div class="form-group">
                    <div class="input-group">
                        <zui:radio name="allowcomment" radios="yesorno" title="允许评论" /></div>
                </div>
                <div class="form-group">
                    <div class="input-group">
                        <zui:select name="contenttplname" data-toggle="selectpicker" options="contenttpls" text="title" value="tpl" title="内容页模板" required="true" /></div>
                </div>
                <div class="form-group">
                    <div class="input-group">
                        <zui:select name="primaltplname" data-toggle="selectpicker" options="listtpls" text="title" value="tpl" title="列表页模板" required="true" /></div>
                </div>
                <div class="form-group">
                    <input type="hidden" id="catid" name="catid" value=0>
                    <button class="btn btn-success" onclick="submit_data();">提交</button></div>
            </form>
            <div id='debug'></div>
        </div>
    </div>
</div>
</block>

<block name="script">
<script type="text/javascript">
//单击事件
function ZtreeClick(event, treeId, treeNode) {
    event.preventDefault();
    var $detail = $('#ztree-detail');

    if ($detail.attr('tid') == treeNode.tId) return;
    $('#catid').val(treeNode.catid);
    $('#catname').val(treeNode.getName());
    $('#contenttplname').val(treeNode.contenttplname).removeClass('n-invalid').selectpicker('refresh');//.data('chosen').results_build();
    $('#primaltplname').val(treeNode.primaltplname).removeClass('n-invalid').selectpicker('refresh');//.data('chosen').results_build();
    $('input[name=allowpublish][value=' + treeNode.allowpublish + ']').iCheck('check');
    $('input[name=allowcomment][value=' + treeNode.allowcomment + ']').iCheck('check');
    $('#upid').val(treeNode.getpId());
    $detail.attr('tid', treeNode.tId);
    $detail.show();
}

//保存属性
function submit_data() {
    var zTree = $.fn.zTree.getZTreeObj("categories_index");
    var name = $('#catname').val(), contenttpl = $('#contenttplname').val(), cattpl = $('#primaltplname').val(), upNode = zTree.getSelectedNodes()[0];

    if (!upNode) {
        $.zui.alertmsg('error', '未选中任何分类！');
        return;
    }

    if(name.length == 0) {
        $.zui.alertmsg('error', '分类名称不能为空！');
        return;
    }
    if(contenttpl.length == 0) {
        $.zui.alertmsg('error', '内容页模板不能为空！');
        return;
    }
    if(cattpl.length == 0) {
        $.zui.alertmsg('error', '列表页模板不能为空！');
        return;
    }
    upNode.catname = name;
    upNode.contenttplname = contenttpl;
    upNode.primaltplname = cattpl;
    zTree.updateNode(upNode);
}
//开始拖拽
function M_BeforeNodeDrag(treeId, treeNodes) {
    var source = [];
    for (var i = 0; i < treeNodes.length; i++) {
        source.push('[' + treeNodes[i].getName() + ']');
    }
    $.zui.debug('开始拖拽：' + source.join(',') + '！\n');
    return true;
}
//监听拖拽事件
function M_BeforeNodeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {
    /*禁止插入层级为2的节点*/
    if (moveType == 'inner' && targetNode.level == 2) {
        return false;
    }
    /*禁止插入剩余层级不足的子节点*/
    if (moveType == 'inner' && treeNodes[0].isParent) {
        var molevel = 2 - targetNode.level; //剩余层级
        var maxlevel = 1;
        var zTree = $.fn.zTree.getZTreeObj("categories_index");
        var nodes = zTree.transformToArray(treeNodes);
        var level = nodes[0].level;

        for (var i = 1; i < nodes.length; i++) {
            if (nodes[i].level == (level + 1)) {
                maxlevel++;
                level++;
            }
        }
        if (maxlevel > molevel) {
            return false;
        }
    }
    return true;
}
//拖拽结束事件
function M_NodeDrop(event, treeId, treeNodes, targetNode, moveType, isCopy) {
    $.zui.debug('拖拽结束！\n');
    var source = [];
    for (var i = 0; i < treeNodes.length; i++) {
        source.push('[' + treeNodes[i].getName() + ']');
    }
    var target = '根目录';
    if (targetNode) {
        target = '[' + targetNode.getName() + ']';
    }
    var type = '';
    switch (moveType) {
    case 'inner':
        type = '里面';
        break;
    case 'prev':
        type = '前面';
        break;
    case 'next':
        type = '后面';
        break;
    default:
        type = moveType;
        break;
    }
    $.zui.debug('将 ' + source.join(',') + ' 拖动到了 ' + target + ' 的 ' + type + '。');
}
//删除结束事件
function M_NodeRemove(event, treeId, treeNode) {
	if(!treeNode.catid) return true;
    var zTree = $.fn.zTree.getZTreeObj("categories_index");
	var url = "{:url('remove')}", data = {catid:treeNode.catid};
	$.ajax({
		url:url, 
		data:data,
		success: function(data){
			if(data.code==1) {
		        $.zui.alertmsg('info', data.msg);
			} else {
		        $.zui.alertmsg('error', data.msg);
	            parent = treeNode.getParentNode();
	            zTree.addNodes(parent, treeNode.getIndex(), treeNode, false);
			}
		},
		error:function(data){
            parent = treeNode.getParentNode();
            zTree.addNodes(parent, treeNode.getIndex(), treeNode, false);
		}
	});
}

$(document).ready(function() {
    $.zui.IS_DEBUG = $('#debug');
});
</script>
</block>